//
//  CreateQRCodeViewController.swift
//  sinaWeibo
//
//  Created by 张国梁 on 16/4/9.
//  Copyright © 2016年 CoderGL. All rights reserved.
//

import UIKit

class CreateQRCodeViewController: UIViewController {

    @IBOutlet weak var QRCodeImageView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "我的名片"
        
        // 生成二维码
        let image = createQRCode()
        // 将生成的二维码图片赋到imageView上
        QRCodeImageView.image = image
    }
    
    
    private func createQRCode() -> UIImage {
        // 1.创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        
        // 2.还原默认属性
        filter?.setDefaults()
        
        // 3.设置滤镜中的值
        filter?.setValue("梁梁梁".dataUsingEncoding(NSUTF8StringEncoding), forKey: "inputMessage")
        
        // 4.取出图片
        let ciImage = filter?.outputImage
        
        return createHighImageWithCIImage(ciImage!, size: 200)
        
        
    }
    
    
    /**
     根据一张CIImage 返回一张高清的UIImage
     - parameter image: CIImage
     - parameter size:  正方形尺寸
     - returns: UIImage
     */
    
    private func createHighImageWithCIImage(image: CIImage, size: CGFloat) -> UIImage {
        
        let extent: CGRect = CGRectIntegral(image.extent)
        let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
        
        // 1.创建bitmap;
        let width = CGRectGetWidth(extent) * scale
        let height = CGRectGetHeight(extent) * scale
        let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
        let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent)
        
        CGContextSetInterpolationQuality(bitmapRef,  CGInterpolationQuality.None)
        CGContextScaleCTM(bitmapRef, scale, scale);
        CGContextDrawImage(bitmapRef, extent, bitmapImage);
        
        // 2.保存bitmap到图片
        let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
        
        return UIImage(CGImage: scaledImage)
    }
}
